package com.xie.authority_system.config.qiniu;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.xie.authority_system.utils.SystemConstants;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 谢金成
 * @date 2024/1/30 19:29
 */
@Component
public class QiniuUtils {

    @Resource
    private QiniuConfig qiniuConfig;

    public String upload(MultipartFile file, String module) {
        Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        String upToken = auth.uploadToken(qiniuConfig.getBucket());
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            InputStream inputStream = file.getInputStream();
            Response response = uploadManager.put(inputStream, null, upToken, null, null);
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return qiniuConfig.getDomain() + putRet.key;
        } catch (QiniuException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }

    public void delete(String url) {
        Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        BucketManager bucketManager = new BucketManager(auth, cfg);
        String key = url.substring(url.lastIndexOf("/") + 1, url.length());
        // 默认头像不能删除
        if (SystemConstants.DEFAULT_AVATAR.equals(key)) {
            return;
        }
        try {
            bucketManager.delete(qiniuConfig.getBucket(), key);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }
}
